const baseUrlDatail = 'https://pic.nbblmc.cn'
let pics = [] // 声明 imageList 变量并初始化为空数组

// 图片直播渲染
function function_name() {
  pics = []
  axios({
    url: `${baseUrlDatail}/api/LivePictureDisplay/list`,
    method: 'GET',
    params: {
      liveId: getUrlKey('liveId'),
      page: 1,
      pageSize: 10,
    },
  }).then((res) => {
    console.log(res)
    pics = res.data.data
    // console.log(imageList)
    console.log(pics)
    const pics_length = pics.length
    console.log(pics_length)
    let pic_index = pics.findIndex((item) => {
      return ~~item.id === ~~id
    })

    console.log(pic_index)
    putPics(pics, pic_index, pics_length)
    //   直接在这里设置滑动条位置
    // setTimeout(() => { // 如果需要一些动画效果，可以保留setTimeout
    //     mid.scrollLeft = pic_index * mid.offsetWidth;
    // }, 0); // 使用0毫秒的setTimeout来立即执行，但允许浏览器处理其他任务

    const progress_info = document.querySelector('.progress-info')
    progress_info.innerHTML = `${pic_index + 1} / ${pics_length}`
    const progress_info_width =
      document.querySelector('.progress-info').offsetWidth
    const line_width = document.querySelector('.line').offsetWidth
    let left = (pic_index / pics_length) * 100 + '%'
    if (
      (pic_index / pics_length) * line_width + progress_info_width >
      line_width
    ) {
      left = line_width - progress_info_width + 'px'
    }
    // const progress_info = document.querySelector('.progress-info')
    progress_info.style.left = left
    // 点击展示高清图片的时候
    const gqBtn = document.querySelector('.gq-btn')
    // 点击高清图
    gqBtn.onclick = function () {
      const item = document.querySelectorAll('.pic')[pic_index]
      console.log(pic_index)
      console.log(item)
      item.setAttribute('src', item.getAttribute('data-GQ'))
      alert('下载高清图成功!')
    }

    // 点击下载
    const download = document.querySelector('.download')
    console.log(download)
    download.onclick = function () {
      alert('图片保存成功!')
      const item = document.querySelectorAll('.pic')[pic_index]
      console.log(item)
      const url = item.getAttribute('data-GQ')
      // console.log(url)
      const id = item.getAttribute('data-id')
      // console.log(id)
      originalImage(id)
      console.log(item.src)
      window.CP2.saveImage({
        url: item.src,
      }).then((res) => {
        console.log(res)
      })
    }
    const transmit = document.querySelector('.transmit')
    transmit.onclick = function () {
      window.CP2.showShare({ title: '图片直播' }).then((res) => {
        console.log(res)
      })
    }
  })
}

// 热门渲染
function function_nameHot() {
  pics = []
  axios({
    url: `${baseUrlDatail}/api/LivePictureDisplay/hotList`,
    method: 'GET',
    params: {
      liveId: getUrlKey('liveId'),
      page: 1,
      pageSize: 10,
    },
  }).then((res) => {
    console.log(res)
    pics = res.data.data
    // console.log(imageList)
    console.log(pics)
    const pics_length = pics.length
    console.log(pics_length)
    let pic_index = pics.findIndex((item) => {
      return ~~item.id === ~~id
    })

    console.log(pic_index)
    putPics(pics, pic_index, pics_length)
    const progress_info = document.querySelector('.progress-info')
    progress_info.innerHTML = `${pic_index + 1} / ${pics_length}`

    //   const progress_info = document.querySelector('.progress-info')
    //   progress_info.innerHTML = `${pic_index + 1} / ${pics_length}`
    const progress_info_width =
      document.querySelector('.progress-info').offsetWidth
    const line_width = document.querySelector('.line').offsetWidth
    let left = (pic_index / pics_length) * 100 + '%'
    if (
      (pic_index / pics_length) * line_width + progress_info_width >
      line_width
    ) {
      left = line_width - progress_info_width + 'px'
    }
    // const progress_info = document.querySelector('.progress-info')
    progress_info.style.left = left

    // 点击展示高清图片的时候
    const gqBtn = document.querySelector('.gq-btn')
    // 点击高清图
    gqBtn.onclick = function () {
      const item = document.querySelectorAll('.pic')[pic_index]
      console.log(pic_index)
      console.log(item)
      item.setAttribute('src', item.getAttribute('data-GQ'))
      alert('下载高清图成功!')
    }

    // 点击下载
    const download = document.querySelector('.download')
    console.log(download)
    download.onclick = function () {
      alert('图片保存成功!')
      const item = document.querySelectorAll('.pic')[pic_index]
      console.log(item)
      const url = item.getAttribute('data-GQ')
      console.log(url)
      const id = item.getAttribute('data-id')
      console.log(id)
      originalImage(id)
      window.CP2.saveImage({
        url: item.src,
      }).then((res) => {
        console.log(res)
      })
    }
    const transmit = document.querySelector('.transmit')
    transmit.onclick = function () {
      window.CP2.showShare({ title: '图片直播' }).then((res) => {
        console.log(res)
      })
    }
  })
}

// 创建一个URL对象
const currentUrl = new URL(window.location)

// 使用URLSearchParams来解析查询字符串
// 从URL中提取查询参数
const queryParams = currentUrl.searchParams

// 检查是否存在type参数，并且其值是否为hotList
const hasHotListType =
  queryParams.has('type') && queryParams.get('type') === 'hotList'

// console.log(hasHotListType)
if (hasHotListType) {
  function_nameHot()
} else {
  function_name()
}

function getUrlKey(name) {
  return (
    decodeURIComponent(
      (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
        location.href
      ) || [, ''])[1].replace(/\+/g, '%20')
    ) || null
  )
}

// 获取点击时候的照片id，从理由地址获取
const _params = window.location.search.split('?')[1].split('&')
const params = {}
_params.forEach((item) => {
  const key = item.split('=')[0]
  const value = item.split('=')[1]
  params[key] = value
})

const id = params.id
console.log('id', id)

const mid = document.querySelector('.mid')
// const progress_info = document.querySelector('.progress-info')

// 点击关闭的时候返回上一页
const close = document.querySelector('.close')
close.onclick = function () {
  console.log('返回上一页')
  window.history.back()
}

function putPics(pics, pic_index, pics_length, progress_info) {
  let html = ''
  // 同时储存普通图片和高清图片
  pics.forEach((item, i) => {
    if (~~item.id !== ~~id) {
      html += `<img src="${item.urlSL}" class="pic"" data-id="${item.id}" style="display: none;" data-src="${item.urlSL}" data-gq="${baseUrlDatail}${item.urlGQ}">`
    } else {
      pic_index = i
      html += `<img src="${item.urlSL}" class="pic"" data-id="${item.id}" style="display: inline-block;" data-src="${item.urlSL}" data-gq="${baseUrlDatail}${item.urlGQ}">`
      showProgressInfo()
    }
  })
  mid.innerHTML = html
  setTimeout(() => {
    document
      .querySelectorAll('.pic')
      .forEach((item) => (item.style.display = 'inline-block'))
    mid.scrollLeft = pic_index * mid.offsetWidth
    // console.log(pic_index * mid.offsetWidth, pic_index, mid.scrollLeft)
  }, 1000)
  let startX, startY, scrollLeft, scrollTop
  mid.addEventListener('touchstart', (e) => {
    console.log(e)
    startX = e.touches[0].clientX
    startY = e.touches[0].clientY
    console.log(startX)
    scrollLeft = mid.scrollLeft
    scrollTop = mid.scrollTop
    console.log(scrollLeft)
  })
  mid.addEventListener('touchmove', (e) => {
    e.preventDefault() // 阻止默认滚动行为
    const x = e.touches[0].clientX
    const y = e.touches[0].clientY
    const walk = (x - startX) * 2 // 根据手指移动的距离来滚动
    const walkY = (y - startY) * 2 // 根据手指垂直移动的距离来滚动
    //  if (Math.abs(walkY) > 20) { // 允许一定范围内的垂直滑动不阻止默认行为
    //   e.preventDefault(); // 阻止默认滚动行为
    // }
    mid.scrollLeft = scrollLeft - walk
    mid.scrollTop = scrollTop - walkY // 根据手指垂直移动的距离来滚动
  })

  mid.addEventListener('touchend', () => {
    const dx = mid.scrollLeft - scrollLeft
    const dy = mid.scrollTop - scrollTop
    console.log(dx)
    console.log(dy)

    // 判断水平滑动
    if (Math.abs(dx) > mid.clientWidth / 2 || mid.scrollLeft === scrollLeft) {
      // 如果滑动距离大于一半屏幕宽度，切换图片
      if (dx > 0 || (mid.scrollLeft === scrollLeft && scrollLeft > 0)) {
        // 向左滑动，显示上一张图片
        console.log('向左滑动，显示上一张图片')
        if (pic_index + 1 === mid.children.length) {
          // 到头了
          console.log('到头了')
        } else {
          pic_index = (pic_index + 1) % mid.children.length
          console.log('当前index', pic_index)
        }
      } else {
        // 向右滑动，显示下一张图片
        // console.log('向右滑动，显示下一张图片', pic_index - 1, (pic_index - 1 + mid.children.length) % mid.children.length, mid.children.length)
        if (pic_index - 1 < 0) {
          // 到头了
        } else {
          pic_index =
            (pic_index - 1 + mid.children.length) % mid.children.length
        }
      }
      mid.scrollLeft = mid.children[pic_index].offsetLeft
    } else {
      // 如果滑动距离小于一半屏幕宽度，回到原位
      mid.scrollLeft = mid.children[pic_index].offsetLeft
    }

    showProgressInfo(pics, pic_index, pics_length)
  })
}

// 监听图片滚动
function showProgressInfo(pics, pic_index, pics_length) {
  const progress_info = document.querySelector('.progress-info')
  progress_info.innerHTML = `${pic_index + 1} / ${pics_length}`
  // 点击展示高清图片的时候
  const gqBtn = document.querySelector('.gq-btn')
  // 点击高清图
  gqBtn.onclick = function () {
    const item = document.querySelectorAll('.pic')[pic_index]
    console.log(pic_index)
    console.log(item)
    item.setAttribute('src', item.getAttribute('data-GQ'))
    alert('下载高清图成功!')
  }

  // 点击下载
  const download = document.querySelector('.download')
  console.log(download)
  download.onclick = function () {
    // 显示“加载中”提示
    // alert('加载中...');
    // alert('图片保存成功!')
    const item = document.querySelectorAll('.pic')[pic_index]
    console.log(item)
    const url = item.getAttribute('data-GQ')
    console.log(url)
    const id = item.getAttribute('data-id')
    console.log(id)
    originalImage(id)
    window.CP2.saveImage({
      url: item.src,
    }).then((res) => {
      console.log(res)
    })
    alert('图片保存成功')
  }

  const progress_info_width =
    document.querySelector('.progress-info').offsetWidth
  const line_width = document.querySelector('.line').offsetWidth
  let left = (pic_index / pics_length) * 100 + '%'
  if (
    (pic_index / pics_length) * line_width + progress_info_width >
    line_width
  ) {
    left = line_width - progress_info_width + 'px'
  }
  progress_info.style.left = left
}

// 原图下载
function originalImage(id) {
  axios({
    url: `${baseUrlDatail}/api/LivePictureDisplay/DownloadImg/${id}`,
    method: 'GET',
  }).then((res) => {
    console.log(res)
  })
}

// 获取直播对象
// function liveObjApi(liveId) {
//     axios({
//         url:`${baseURL}/api/LivePictureDisplay/liveObj/${liveId}`,
//         method:'GET',
//     }).then((res)=> {
//       console.log(res)
//       headerUrl = res.data.data.photoUrl
//       liveName = res.data.data.name
//       watchNumber = res.data.data.watchNumber
//       console.log(watchNumber)
//       ifPush = res.data.data.ifPush
//       ifShare = res.data.data.ifShare
//       address = res.data.data.address
//       timeStamp = res.data.data.endTime
//       status=res.data.data.status
//       console.log(status)
//       // 创建一个Date对象
//       const date = new Date(timeStamp)
//       endTime = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2);
//       console.log(endTime)
//         // 获取页面上所有的 'transmit' 元素
//       const shares = document.querySelectorAll('.transmit');
//       console.log(shares)
//     //   if (ifShare === 1) {
//     // share.style.display = 'block'; // 或者使用 'flex', 'inline' 等
//     // } else {
//     // share.style.display = 'none';
//     // }

//          // 根据 status 的值来开启或关闭定时器
//     if (status === 1) {
//       // 如果 status 为 1，开启定时器
//       renderInterval = setInterval(imageRender, 20000);
//       // 使用 setInterval 调用 imageRender 函数，周期为 20000 毫秒（20秒）
//       renderHotInterval = setInterval(hotImageRander, 20000);
//       // 每隔20秒调用一次 liveObjApi 函数
//       renderObjInterval = setInterval(function() {
//          liveObjApi(liveId)
//           }, 20000)
//     } else if (status === 0 && renderInterval && hotImageRander && renderObjInterval) {
//       // 如果 status 为 0，并且定时器已经开启，则关闭定时器
//       clearInterval(renderInterval);
//       clearInterval(hotImageRander)
//       clearInterval(renderObjInterval)
//     }
//     //   console.log(1)
//       document.querySelector('.headerUrl').src=headerUrl
//       document.querySelector('.tcHeaderUrl').src=headerUrl
//       document.querySelector('.watchNumber').innerHTML=watchNumber
//       document.querySelector('.liveName').innerHTML=liveName
//       document.querySelector('.tcTitle').innerHTML=liveName
//       document.querySelector('.zj').innerHTML=address
//       document.querySelector('.rq').innerHTML = endTime

//     })
// }
